<template>
  <div class="product-list">
    <div v-for="product in products" :key="product.id" class="product-item">
      ({{ product.id }}){{ product.name }} - ¥{{ product.price }}
    </div>

    <div v-if="loading" class="loading">
      加载中...
    </div>

    <div v-if="!hasMore && !loading" class="no-more">
      没有更多商品了
    </div>
  </div>
</template>


<script setup lang="ts">
import { useProductStore } from '@/stores/productStore.ts'
import { onMounted, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'

const productStore = useProductStore()
const { products, loading, hasMore, isEmpty } = storeToRefs(productStore)
// 无限滚动逻辑
const handleScroll = () => {
  if (
    window.innerHeight + window.scrollY >= document.body.offsetHeight - 200
  ) {
    if (productStore.loading) return
    console.log(`触底了,开始加载第${productStore.page}页`)
    productStore.fetchProducts()
  }
}

onMounted(() => {
  // 初始加载
  productStore.initProducts()
  // 添加滚动监听
  window.addEventListener('scroll', handleScroll)
})
onUnmounted(() => {
  // 移除滚动监听
  window.removeEventListener('scroll', handleScroll)
})


</script>


<style scoped>
.product-list {
  display: flex;
  flex-direction: column;
}

.product-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.loading,
.no-more {
  text-align: center;
  padding: 20px;
  color: #999;
}
</style>
